<template>
  <div>
    <el-form
      ref="editForm"
      :model="record"
      :rules="formRules"
      label-width="80px"
    >
      <!-- <el-form-item
        label="ID"
        prop="id"
        label-width="70px">
        <el-col :span="22">
          <el-input v-model="record.id"/>
        </el-col>
      </el-form-item> -->
      <el-form-item
        label="名称"
        prop="title"
      >
        <el-col :span="22">
          <el-input v-model="record.title" placeholder="菜单名称" />
        </el-col>
      </el-form-item>
      <el-form-item
        label="菜单角色"
        prop="checkedPart1"
      >
        <el-col :span="22" class="checkbox-group">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="checkedPart" size="mini" @change="handlecheckedPartChange">
            <el-checkbox v-for="role in rolesOptions" :key="role['id']" :label="role['role']" name="checkedPart" class="checkboxContent" border>{{ role['description'] }}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-form-item>

      <!-- <el-form-item
        label="类型"
        prop="type"
        label-width="70px">
        <el-col :span="22">
          <ef-dict-select
            v-model="record.type"
            clearable
            style="width: 100%;"
            prop="type"
            placeholder="类型"
            dict-type="MENU_TYPE"/>
        </el-col>
      </el-form-item> -->

      <el-form-item
        label="路径"
        prop="path"
      >
        <el-col :span="22">
          <el-input v-model="record.path" placeholder="URL链接，如父菜单：/menu，子菜单：/menu/index" />
        </el-col>
      </el-form-item>
      <el-form-item
        label="重定向"
        prop="redirect"
      >
        <el-col :span="22">
          <el-input v-model="record.redirect" placeholder="重定向地址，在面包屑中点击会重定向去的地址" />
        </el-col>
      </el-form-item>
      <el-form-item
        label="文件路径"
        prop="component"
      >
        <el-col :span="22">
          <el-input v-model="record.component" placeholder="VUE文件路径，父菜单填Layout，子菜单填具体文件路径如：module/menu/sysMenu" />
        </el-col>
      </el-form-item>
      <el-form-item
        label="路由名"
        prop="name"
      >
        <el-col :span="22">
          <el-input v-model="record.name" placeholder="VUE文件里的name" />
        </el-col>
      </el-form-item>
      <el-form-item
        label="图标"
        prop="icon"
      >
        <el-row :gutter="10">
          <el-col :span="16">
            <e-icon-picker v-if="!useCustomizeIcon" v-model="record.icon" size="mini" placeholder="显示的图标" />
            <el-input v-else v-model="record.icon" placeholder="显示的图标" />
          </el-col>
          <el-col :span="6">
            <el-checkbox v-model="useCustomizeIcon">自定义</el-checkbox>
          </el-col>
        </el-row>
      </el-form-item>
      <el-row>
        <el-col :span="10">
          <el-form-item
            prop="isShow"
            label="是否显示"
          >
            <el-switch
              v-model="record.isShow"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            prop="alwaysShow"
            label="总是显示"
          >
            <el-switch
              v-model="record.alwaysShow"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item
            prop="breadcrumb"
            label="面包屑中显示"
          >
            <el-switch
              v-model="record.breadcrumb"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            prop="affix"
            label="固钉"
          >
            <el-switch
              v-model="record.affix"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        prop="noCache"
        label="无缓存"
      >
        <el-switch
          v-model="record.noCache"
          :active-value="true"
          :inactive-value="false"
        />
      </el-form-item>
      <el-form-item
        label="排序"
        prop="sort"
      >
        <el-col :span="22">
          <el-input-number
            v-model="record.sort"
            class="ef-input-number"
            controls-position="right"
            placeholder="菜单排序"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        label="菜单配置"
        prop="menuManage"
      >
        <el-col :span="22">
          <el-tree
            ref="menuTree"
            v-loading="menuTreeLoading"
            :data="menuData"
            show-checkbox
            :props="defaultProps"
            :check-strictly="true"
            accordion
            node-key="path"
            @check="handleCheck"
          />
        </el-col>
      </el-form-item>
      <div style="text-align: center">
        <el-button
          type="primary"
          :loading="submitLoading"
          @click.native.prevent="handleSubmit"
        >
          <i class="fa fa-save" /> 保存</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
// import { lengthValidator } from '@/utils/index'
import MenuApi from '../api/menu-api'
import SysRoleApi from '@/modules/sys_role/api/sysRole'
import { Message } from 'element-ui'
// import store from '@/store'
/* eslint-disable */
export default {
  name: 'SysMenuEdit',
  components: {
  },
  props: {
    mode: {
      type: String
    },
    record: {
      type: Object
    }
  },
  data() {
    return {
      useCustomizeIcon: false,
      checkAll: false,
      submitLoading: false,
      isIndeterminate: true,
      // 角色列表
      rolesOptions: [],
      checkedKey: undefined,
      rolesList: [],
      checkedPart:[],
      menuTreeLoading: false,
      menuData: [],
      checkedPart1:[],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            max: 100,
            message: '最大长度不能超过100个字符',
            trigger: 'blur'
          }
        ],
        title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            max: 32,
            message: '最大长度不能超过100个字符',
            trigger: 'blur'
          }
        ],
        checkedPart: [{ type: 'array', required: true, message: '至少选择一个部分', trigger: 'change' }],
        path: [
          { required: true, message: '请输入链接', trigger: 'blur' },
          {
            max: 200,
            message: '最大长度不能超过200个字符',
            trigger: 'blur'
          }
        ],
        permission: [
          {
            max: 100,
            message: '最大长度不能超过100个字符',
            trigger: 'blur'
          }
        ],
        menuIcon: [
          {
            max: 255,
            message: '最大长度不能超过255个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    record: function (newValue) {
      if(this.record.meta){
        console.log(this.record.meta)
        this.checkedPart = this.record.meta.roles;
      }
    }
  },
  mounted() {
    this.init(this.record)
  },
  methods: {
    init(row){
      this.record = row;
      this.getAllRole();
      this.getVueModuleDirTree();
      if(row.meta){
        this.checkedPart = row.meta.roles;
      }
    },
    getVueModuleDirTree() {
      this.menuTreeLoading = true
      MenuApi.getVueModuleDirTree().then(response => {
        const data = response.data
        if (data.code === 200) {
          this.menuData = data.data
        } else {
          Message.error(data.message)
        }
        this.menuTreeLoading = false
      })
    },
    handleCheck(data) {
      if (this.checkedKey === data.path) {
        this.$refs.menuTree.setCheckedKeys([]);
        this.checkedKey = undefined
        this.record.component = ''
        this.record.name = ''
      } else {
        this.$refs.menuTree.setCheckedKeys([data.path]);
        this.checkedKey = data.path
        let path = data.path
        if(path.indexOf('\\\\')>0){
          path = path.replaceAll('\\\\','/')
        }
        if(path.indexOf('\\')>0){
          path = path.replaceAll('\\','/')
        }
        if(path.indexOf('.vue')>0){
          // 取src/后面的
          path = path.split("src/")[1]
          // 取.vue前面的
          path = path.split(".")[0]
          this.record.component = path
          let nameIndex = path.lastIndexOf("/");
          //截取最后一个/后的值
          let name = path.substring(nameIndex + 1, path.length);
          this.record.name = name
        }

      }
      // console.log(this.$refs.menuTree.getCheckedKeys())
    },
    handleSubmit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          this.submitLoading = true
          let parentId;
          let meta = {
            "title":"",
            "icon":"",
            "roles":[],
            "noCache": false,
            "affix": false,
            "breadcrumb": true
          }
          //添加二级菜单
          meta.title = this.record.title;
          meta.noCache = this.record.noCache;
          meta.affix = this.record.affix;
          meta.breadcrumb = this.record.breadcrumb;
          meta.icon = this.record.icon;
          meta.roles = this.checkedPart;
          if(this.record.parentId){
              parentId = this.record.parentId
          }
          if (this.mode === 'add') {
            //新增需要添加isChildren字段
            let isChildren;
            let node;
            if(!this.record.parentId){
              isChildren = false
              node = 0
            }else{
              isChildren = true
              node = 1
            }
            const newRecord = Object.assign({}, this.record, {
              meta:meta,
              isChildren:isChildren,
              node:node
            })
            //添加菜单
            MenuApi.add(newRecord).then(response =>{
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: "添加成功!",
                  type: 'success'
                });
                this.$emit('after-edit',{pid:parentId})
              }else{
                this.$message({
                  message: data.message,
                  type: 'danger'
                });
              }
            })
            // console.log(newRecord)
          } else {
            const newRecord = Object.assign({}, this.record, {
              meta:meta
            })
            //修改菜单信息
            MenuApi.update(newRecord).then(response =>{
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: "修改成功!",
                  type: 'success'
                });
                this.$emit('after-edit',{pid:parentId})
              }else{
                this.$message({
                  message: data.message,
                  type: 'danger'
                });
              }
            })
          }
          this.submitLoading = false
        } else {
          return false
        }
      })
    },
    resetFields() {
      // this.$refs['editForm'].resetFields()
      this.checkedPart = []
    },
    handleCheckAllChange(val) {
      this.checkedPart = val ? this.rolesList : []
      this.isIndeterminate = false
    },
    handlecheckedPartChange(value) {
      // console.log(this.checkedPart)
      const checkedCount = value.length
      this.checkAll = checkedCount === this.rolesList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.rolesList.length
    },
    getAllRole() {
        SysRoleApi.query().then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.rolesOptions = data.list
              for (var role in data.list) {
                this.rolesList.push(data.list[role].role)
              }
            }
        })
    }
  }
}
</script>
<style>
.checkbox-group .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px;
}
</style>
